package com.skytech.tax.customsdatawarehouse.singlewindow.customsdeclarations.domain.dao;

import com.skytech.tax.customsdatawarehouse.singlewindow.customsdeclarations.domain.entity.IECustomsDeclaration;
import com.skytech.tax.customsdatawarehouse.singlewindow.customsdeclarations.domain.entity.IECustomsDeclarationFile;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lianhong
 * @since 2021/11/29
 */
@Repository("singleWindow.ieCustomsDeclarationFileDao")
public class IECustomsDeclarationFileDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private String existsCustomsDeclarationFileSql = "SELECT count(1) FROM gd_jckhwgd_file WHERE cusCiqNo = ?";

    public boolean exists(String cusCiqNo) {
        Integer count = namedParameterJdbcTemplate.getJdbcOperations()
                .queryForObject(this.existsCustomsDeclarationFileSql, new Object[]{cusCiqNo}, Integer.class);
        return count != null && count > 0;
    }

    private String selectCustomsDeclarationFileSql = "SELECT file, storageTime FROM gd_jckhwgd_file WHERE cusCiqNo = ?";

    public IECustomsDeclarationFile findByCusCiqNo(String cusCiqNo) {
        return namedParameterJdbcTemplate.getJdbcOperations().queryForObject(selectCustomsDeclarationFileSql,
                new Object[]{cusCiqNo}, new BeanPropertyRowMapper<>(IECustomsDeclarationFile.class));
    }

    private String insertCustomsDeclarationFileSql = "INSERT INTO gd_jckhwgd_file (cusCiqNo, file, storageTime) VALUES (:cusCiqNo, :file, :storageTime)";

    public void save(IECustomsDeclarationFile customsDeclarationFile) {
        customsDeclarationFile.setStorageTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        this.namedParameterJdbcTemplate.update(this.insertCustomsDeclarationFileSql, new BeanPropertySqlParameterSource(customsDeclarationFile));
    }

    private String deleteCustomsDeclarationFileSql = "DELETE FROM gd_jckhwgd_file WHERE cusCiqNo = ?";

    public void delete(String cusCiqNo) {
        this.namedParameterJdbcTemplate.getJdbcOperations().update(this.deleteCustomsDeclarationFileSql, cusCiqNo);
    }
}
